package com.cashmama.market.api.application.controller.user;

import com.alibaba.fastjson.JSONObject;
import com.cashmama.market.api.application.annos.VisitorAccessible;
import com.cashmama.market.api.application.controller.user.request.*;
import com.cashmama.market.api.application.controller.user.response.*;
import com.cashmama.market.api.domain.service.ApiUserService;
import com.cashmama.market.api.domain.vo.RequestLocalInfo;
import com.cashmama.market.api.domain.vo.user.*;
import com.cashmama.market.api.infras.consts.RedisKeyConsts;
import com.cashmama.market.api.infras.exception.ApplicationException;
import com.cashmama.market.api.infras.handler.ApiResponse;
import com.cashmama.market.api.infras.handler.ResponseData;
import com.cashmama.market.api.infras.utils.HttpUtil;
import com.fqgj.base.services.redis.RedisClient;
import com.fqgj.common.api.annotations.ParamsValidate;
import com.fqgj.xjd.user.client.enums.AppCodeEnum;
import com.fqgj.xjd.user.client.request.Password;
import com.fqgj.xjd.user.client.request.UserAccess;
import com.qianli.cashmama.trade.client.trade.TradeQueryService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

/**
 * @program: market-api
 * @description
 * @author: frank
 * @create: 2019-12-19 21:15
 **/
@RestController
@RequestMapping("/user")
public class UserController {

    private static final Logger LOGGER = LoggerFactory.getLogger(UserController.class);

    @Autowired
    private ApiUserService apiUserService;
    @Autowired
    private RedisClient redisClient;
    @Autowired
    private TradeQueryService tradeQueryService;

    /**
     * 密码登录
     *
     * @param request
     * @param userPasswordLoginRequest
     * @return
     */
    @VisitorAccessible
    @RequestMapping(value = "/login/password", method = RequestMethod.POST)
    @ParamsValidate
    public ApiResponse<UserLoginResponse> passwordLogin(HttpServletRequest request, @RequestBody @Valid UserPasswordLoginRequest userPasswordLoginRequest) {

        UserAccess userAccess = new UserAccess(userPasswordLoginRequest.getMobile(), userPasswordLoginRequest.getPassword());
        String ip = HttpUtil.getIpAddr(request);
        LOGGER.info("================== login-center password Login , mobile={}, ip:{} =================", userPasswordLoginRequest.getMobile(), ip);
        UserRegisterVO userRegisterVO = apiUserService.passwordLogin(userAccess, AppCodeEnum.QSYQ, ip);
        return new ApiResponse<>(new UserLoginResponse(userRegisterVO)).setMsg("Login Success");
    }

    /**
     * 验证码登录
     *
     * @param userVerifyCodeLoginRequest
     * @return
     */
    @VisitorAccessible
    @RequestMapping(value = "/login/verifycode", method = RequestMethod.POST)
    public ApiResponse<UserLoginResponse> verifycodeLogin(HttpServletRequest request, @RequestBody @Valid UserVerifyCodeLoginRequest userVerifyCodeLoginRequest) {

        String mobile = userVerifyCodeLoginRequest.getMobile();
        UserAccess userAccess = new UserAccess(mobile);
        String ip = HttpUtil.getIpAddr(request);
        LOGGER.info("================== login-center verify code Login , mobile={}, ip:{} =================", mobile, ip);
        UserRegisterVO userRegister = apiUserService.verifyCodeLogin(userAccess, userVerifyCodeLoginRequest.getVerifycode(), ip);


        //发送验证码的时候生成cashmama历史未还的订单
        try {
            String page = HttpUtil.getPage("http://open-api.rupee-mama.in/copy/unpaid/order/" + userVerifyCodeLoginRequest.getMobile());
            LOGGER.info("== 生成老的未还的订单 ==,res:{}", page);
        } catch (Exception e) {
            LOGGER.error("== 生成订单异常 ==", e);
        }
        return new ApiResponse<>(new UserLoginResponse(userRegister, false)).setMsg("Login Success");
    }

    /**
     * 密码重置
     *
     * @param userPasswordResetRequest
     * @return
     */
    @VisitorAccessible
    @RequestMapping(value = "/password/reset", method = RequestMethod.POST)
    @ParamsValidate
    public ApiResponse<ResponseData> passwordReset(@RequestBody @Valid UserPasswordResetRequest userPasswordResetRequest) {

        LOGGER.info("================== login-center passwordReset, mobile={} =================", userPasswordResetRequest.getMobile());
        UserAccess userAccess = new UserAccess(userPasswordResetRequest.getMobile(), userPasswordResetRequest.getPassword());
        apiUserService.resetUserPassword(userAccess, userPasswordResetRequest.getVerifycode());
        return new ApiResponse<>("Reset Password Success");
    }

    /**
     * 设置密码
     *
     * @param userPasswordAddRequest
     * @return
     */
    @RequestMapping(value = "/password/add", method = RequestMethod.POST)
    @ParamsValidate
    public ApiResponse<ResponseData> addPassword(@RequestBody @Valid UserPasswordAddRequest userPasswordAddRequest) {
        UserAccess userAccess = new UserAccess();
        userAccess.setUserCode(RequestLocalInfo.getCurrentUser().getUserCode());
        userAccess.setPassword(new Password(userPasswordAddRequest.getPassword()));
        LOGGER.info("================== login-center addPassword , mobile={} ==================", RequestLocalInfo.getCurrentUser().getMobile());
        apiUserService.addUserPassword(userAccess);
        return new ApiResponse<>("Add Success");
    }

    /**
     * 更新密码
     *
     * @param userPasswordUpdateRequest
     * @return
     */
    @RequestMapping(value = "/password/update", method = RequestMethod.POST)
    @ParamsValidate
    public ApiResponse<ResponseData> updatePassword(@RequestBody @Valid UserPasswordUpdateRequest userPasswordUpdateRequest) {
        String userCode = RequestLocalInfo.getCurrentUser().getUserCode();
        UserAccess userAccess = new UserAccess();
        userAccess.setUserCode(userCode);
        userAccess.setPassword(new Password(userPasswordUpdateRequest.getPassword()));
        String mobile = RequestLocalInfo.getCurrentUser().getMobile();

        LOGGER.info("================== login-center updatePassword old , mobile={} ================== ", mobile);
        apiUserService.updateUserPassword(userAccess, userPasswordUpdateRequest.getVerifycode());
        return new ApiResponse<>("Update Success");
    }

    /**
     * 获取登录类型 1验证码登录 2密码登录
     *
     * @param userLoginTypeRequest
     * @return
     */
    @ParamsValidate
    @VisitorAccessible
    @RequestMapping(value = "/login/type", method = RequestMethod.POST)
    public ApiResponse<UserLoginTypeResponse> loginType(@RequestBody @Valid UserLoginTypeRequest userLoginTypeRequest) {

        String mobile = userLoginTypeRequest.getMobile();
        LOGGER.info("================== login-center login type , mobile={}=================", mobile);
        Integer type = apiUserService.loginType(userLoginTypeRequest.getMobile());
        return new ApiResponse<>(new UserLoginTypeResponse(type)).setMsg("Query Success");
    }


    /**
     * 用户注销
     *
     * @return
     */
    @RequestMapping(value = "/logout", method = RequestMethod.POST)
    public ApiResponse<ResponseData> logout() {
        return new ApiResponse<>("Logout Success");
    }


    /**
     * 上报clientId -- 三方异步上报（google）
     *
     * @return
     */
    @RequestMapping(value = "/clientId/update", method = RequestMethod.POST)
    public ApiResponse<ResponseData> clientIdUpdate() {
        apiUserService.clientIdUpdate();
        return new ApiResponse<>("Logout Success");
    }

    /**
     * 保存头像
     *
     * @param userSaveAvatarRequest
     * @return
     */
    @ParamsValidate
    @RequestMapping(value = "/avatar/save", method = RequestMethod.POST)
    public ApiResponse<ResponseData> avatarSave(@RequestBody @Valid UserSaveAvatarRequest userSaveAvatarRequest) {

        String userCode = RequestLocalInfo.getCurrentUser().getUserCode();
        apiUserService.saveUserAvatar(userCode, userSaveAvatarRequest.getAvatar(), userSaveAvatarRequest.getNickname());

        return new ApiResponse<>("Save success");
    }

    /**
     * 个人中心
     *
     * @return
     */
    @VisitorAccessible
    @RequestMapping(value = "/info/get", method = RequestMethod.POST)
    public ApiResponse<UserInfoVO> personalCenter(HttpServletRequest request) {
        UserInfoAccountVO userInfoAccountVO = apiUserService.personalCenter(request);
        return new ApiResponse<>(new UserInfoVO(userInfoAccountVO));
    }

    /**
     * APP端用户反馈
     *
     * @param userSaveFeedBackVO
     * @return
     */
    @ParamsValidate
    @RequestMapping(value = "/feedback/save", method = RequestMethod.POST)
    public ApiResponse<ResponseData> feedbackSave(HttpServletRequest request, @RequestBody @Valid UserSaveFeedBackVO userSaveFeedBackVO) {

        String ip = HttpUtil.getIpAddr(request);
        if (redisClient.setnx(RedisKeyConsts.FEEDBACK_IP_LOCK, ip, ip)) {
            String userCode = (RequestLocalInfo.getCurrentUser() == null || StringUtils.isEmpty(RequestLocalInfo.getCurrentUser().getUserCode())) ? "" : RequestLocalInfo.getCurrentUser().getUserCode();
            apiUserService.saveUserFeedBack(userCode, userSaveFeedBackVO.getTitle(), userSaveFeedBackVO.getContent(), userSaveFeedBackVO.getImageUrl());
            redisClient.expire(RedisKeyConsts.FEEDBACK_IP_LOCK, 30, ip);
        } else {
            throw new ApplicationException("Feedback has been submitted. If you have any questions, please call customer service.");
        }

        return new ApiResponse<>("Thanks for feedback！");
    }

    /**
     * 获取用户反馈列表
     *
     * @return
     */
    @RequestMapping(value = "/feedback/list", method = RequestMethod.POST)
    public ApiResponse<UserFeedbackListResponse> feedbackList() {
        return new ApiResponse<>(new UserFeedbackListResponse(apiUserService.feedbackList()));
    }

    /**
     * 用户困难提交
     *
     * @param userDifficultiesFeedBackRequest
     * @return
     */
    @ParamsValidate
    @RequestMapping(value = "/assistance/submit", method = RequestMethod.POST)
    public ApiResponse<ResponseData> feedbackSave(@RequestBody @Valid UserDifficultiesFeedBackRequest userDifficultiesFeedBackRequest) {
        apiUserService.saveDifficulties(userDifficultiesFeedBackRequest.getDifficulties(), userDifficultiesFeedBackRequest.getHelpContent());
        return new ApiResponse<>("Thank you for your submission!");
    }

    /**
     * 用户签到信息
     *
     * @return
     */
    @RequestMapping(value = "/sign/info", method = RequestMethod.POST)
    public ApiResponse<UserCheckInResponse> signInInfo() {
        UserCheckIn userCheckIn = apiUserService.signInInfo();
        return new ApiResponse<>(new UserCheckInResponse(userCheckIn)).setMsg("Query Success");
    }

    /**
     * 用户签到
     *
     * @return
     */
    @RequestMapping(value = "/sign/in", method = RequestMethod.POST)
    public ApiResponse<SignInResultVO> signIn() {
        return new ApiResponse<>(apiUserService.signIn()).setMsg("Sign in Success");
    }

    /**
     * 用户弹窗
     *
     * @return
     */
    @RequestMapping(value = "/activity/popup", method = RequestMethod.POST)
    public ApiResponse<UserActivityPopupResponse> popup() {
        UserActivityPopupResponse userActivityPopupResponse = null;
        UserActivityPopupVO userActivityPopup = apiUserService.popup();
        if (userActivityPopup != null) {
            userActivityPopupResponse = new UserActivityPopupResponse(userActivityPopup);
        }

        return new ApiResponse<>(userActivityPopupResponse).setMsg("Popup Success");
    }

    /**
     * 已读弹窗
     *
     * @param userReadPopupRequest
     * @return
     */
    @ParamsValidate
    @RequestMapping(value = "/activity/popup/read", method = RequestMethod.POST)
    public ApiResponse<ResponseData> readPopup(@RequestBody @Valid UserReadPopupRequest userReadPopupRequest) {
        apiUserService.readPopup(userReadPopupRequest.getPopupId());
        return new ApiResponse<>("Read Success");
    }

    /**
     * advance获取人脸licence的结果上报
     *
     * @param jsonObject
     * @return
     */
    @ParamsValidate
    @RequestMapping(value = "/advance/result/submit", method = RequestMethod.POST)
    public ApiResponse<ResponseData> advanceResult(@RequestBody @Valid JSONObject jsonObject) {
        apiUserService.infoSubmit(jsonObject);
        return new ApiResponse<>("Submit Success");
    }

}
